<template>
  <div class="container">
    <div class="app-container">
      <el-tree
        :data="deps"
        :props="defaultProps"
        @node-click="handleNodeClick"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template v-slot="{ data }">
          <el-row type="flex" style="width: 100%; height: 40px" align="middle">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4" style="text-align: right">
              <span class="tree-manager">{{ data.managerName }}</span>
              <el-dropdown @command="handleCommand($event, data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
      <Dialogdep 
      ref="dep"
      :showDialog.sync="showDialog" 
      :originDeps="originDeps"
      :currentNodeId="currentNodeId"
      @updateDeps="getDepartments" />
  </div>
</template>
<script>
import { getDepartmentsApi, delDeps } from "@/api/department";
import { transListToTree } from '@/utils/index'
import Dialogdep from '@/views/department/components/Dialogdep.vue'
export default {
  name: "Department",
  components: {
    Dialogdep
  },
  data() {
    return {
      deps: [],
      originDeps:[],
      currentNodeId:'',
      showDialog:false,
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  created() {
    this.getDepartments()
  },
  methods: {
    async getDepartments() {
      const res = await getDepartmentsApi();
      this.originDeps = res 
      this.deps = transListToTree(res, 0)
    },
    handleNodeClick(data) {
      // console.log(data);
    },
    handleCommand(command, id) {
      if(command === 'add'){
        this.showDialog = true
        this.currentNodeId = id
      } else if (command === 'edit') {
        this.showDialog = true
        this.currentNodeId = id
        // vue 更新 props 是异步的
        this.$nextTick(()=>{
          this.$refs.dep.getDepsDetail()
        })
      } else {
        this.$confirm('确定要删除该部门吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() =>{
          await delDeps(id)
          this.$message.success('删除成功')
          this.getDepartments()
        })
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 50px;
  margin-right: 10px;
  display: inline-block;
}
</style>
